<template>
  <div>
    <van-sticky>
        <van-nav-bar style="background-color:#409eff" left-arrow left-text=""
        @click-left="onClickLeft">
          <template #title>
            <div style="color:white">
              菜品分类
            </div>
          </template>
          <template #left>
            <div style="color:white">
              <van-icon name="arrow-left" color="white" />
              返回
            </div>
          </template>
        </van-nav-bar>
      </van-sticky>


    <van-cell-group inset>
      <van-cell size="large" title="配送地址" icon="location-o" @click="getAddressList">
        <template #label>
          <!-- 如果后期加入默认地址 可在计算属性中进行筛选 进行显示 目前默认显示数组的第一个地址 -->
          <van-row>
            <van-col span="8">姓名:{{username}}</van-col>
            <van-col span="16">电话:{{tel}}</van-col>
          </van-row>
          <van-row>
            <van-col span="24">地址:{{address}}</van-col>
          </van-row>
        </template>
      </van-cell>

      <!-- 订单详情 -->
      <van-cell size="large" title="订单详情" icon="orders-o">
        <template #label>
          <van-row v-for="line of orderLines.values()" :key="line.productId">
            <van-col span="8">{{line.name}}</van-col>
            <van-col span="8">￥{{line.price}}</van-col>
            <van-col span="8">x{{line.num}}</van-col>
          </van-row>
          <van-row style="border-top:1px dotted #ededed">
            <van-col span="13"></van-col>
            <van-col span="13">总计:￥{{total}}</van-col>
          </van-row>
        </template>
      </van-cell>
      <van-field v-model="buyerMessage" rows="2" autosize label="买家留言" left-icon="comment-o" type="textarea"
        maxlength="50" placeholder="请输入留言" show-word-limit />
    </van-cell-group>

    <div class="confirm_btn" @click="confirm">确认提交</div>


    <!-- 充值 -->
    <van-action-sheet v-model="balanceShow" title="充值" @close="toClose">
      <van-form validate-first @submit="topUp">
        <!-- 通过 validator 进行函数校验 -->
        <van-field v-model="balance" name="validator" label="充值金额" placeholder="请输入充值金额"
          :rules="[{ validator, message: '单次充值金额不超过1000元' }]" />
        <div style="margin: 16px;">
          <van-button color="#7879FF" round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </van-action-sheet>

    <!-- 地址选择弹窗 -->
    <van-action-sheet v-model="showAddress" title="选择地址">
      <div class="content">
        <van-address-list v-model="chosenAddressId" :list="addressList" add-button-text="确定" @add="onSave">
        </van-address-list>
      </div>
    </van-action-sheet>
  </div>
</template>
<script>
  import {
    mapState,
    mapActions,
    mapGetters
  } from 'vuex'
  export default {
    name: '',
    data() {
      return {
        // 被选中的地址id
        chosenAddressId: '1',
        // 面板弹出控制
        showAddress: false,
        // 姓名
        username: '',
        // 电话
        tel: '',
        // 地址
        address: '',
        // 充值框弹出
        balanceShow: false,
        // 充值金额
        balance: '',
        // 买家留言
        buyerMessage: ''
      }
    },

    computed: {
      // 获取保存的订单信息
      ...mapState('shopcar', ['orderLines']),
      // 获取订单总价
      ...mapGetters('shopcar', ['total']),
      // 获取地址列表
      ...mapState('address', ['addressData']),
      // 获取用户信息
      ...mapState('user', ['userInfo']),
      // 根据地址数据生成匹配组件的地址数据
      addressList() {
        // 筛选地址数据 生成匹配组件的数据
        let addressArr = this.addressData
        let addressList = []
        if (!addressArr) {
          return;
        }
        addressArr.forEach((item, index) => {
          let addressObj = {}
          addressObj.id = item.id,
            addressObj.name = item.realname,
            addressObj.tel = item.telephone,
            addressObj.address = item.province + item.city + item.area + item.address,
            addressObj.isDefault = item.isDefault
          addressList.push(addressObj)
        });
        return addressList;
      }
    },

    methods: {
      // 获取地址数据
      ...mapActions('address', ['getAddressData']),
      // 获取用户信息
      ...mapActions('user', ['getUserInfo']),
      // 提交订单
      ...mapActions('order', ['SubmitOrder']),
      // 获取地址数据
      getAddressList() {
        // 打开actionSheet
        this.showAddress = true
        // 获取地址数据
        this.getAddressData(this.userInfo.id)
      },
      onClickLeft() {
        this.$router.go(-1)
        console.log();
        // setTimeout(() => {
        //   this.$store.state.shopcar.orderLines.clear()
        // }, 500);
      },
      // 选择地址确认
      onSave() {
        // console.log(this.chosenAddressId);
        // 根据地址id筛选当前选择的地址
        let addressObj = this.addressData.filter((item, index) => {
          return item.id === this.chosenAddressId
        });
        // 根据选择的地址进行地址的更新
        this.username = addressObj[0].realname
        this.tel = addressObj[0].telephone
        this.address = addressObj[0].province + addressObj[0].city + addressObj[0].area + addressObj[0].address
        // 隐藏地址选择面板
        this.showAddress = false
      },
      confirm() {
        // 保存订单信息
        // 参数
        var obj = {
          addressId: this.chosenAddressId,
          customerId: this.userInfo.id,
          buyerMessage: this.buyerMessage,
          orderLines: Array.from(this.orderLines.values())
        }
        this.SubmitOrder(obj)
          .then((response) => {
            if (response.data.message == '余额不足!') {
              Dialog.confirm({
                  confirmButtonColor: '#409eff',
                  message: "当前余额不足，是否充值？",
                })
                .then(() => {
                  // on confirm
                  // 弹出充值框
                  this.balanceShow = true
                })
                .catch(() => {
                  // on cancel
                });
            } else if (response.data.message == '操作成功') {
              this.$toast.success('操作成功')
              // 路由跳转至订单页面
              this.$router.push({
                  path: '/manager/order'
                })
                .then((res) => {
                  // 获取订单数据
                })
            } else {
              this.$toast.error('操作失败')
            }
          })
      },
      // 充值金额校验函数返回 true 表示校验通过，false 表示不通过
      validator(val) {
        if (val < 0 || val > 1000) {
          return false
        } else {
          return true
        }
      },
      // 充值
      topUp() {
        console.log(this.balance, this.userInfo.id);
        let data = {
          customerId: this.userInfo.id,
          money: this.balance
        }
        this.getRecharge(data).then(r => {
          console.log(r);
          if (r.data.status == 200) {
             this.$toast.success(r.data.message)
            this.balanceShow = false
          } else {        
            this.$toast.error( r.data.message)
          }
        })
        // 实现充值逻辑
      },
      // 取消弹框
      toClose() {
        // 余额置空
        this.balance = ''
      },
    },
    created() {

      // 获取用户信息
      this.getUserInfo().then(r => {
        // 获取地址信息  并设置默认地址
        this.getAddressData(this.userInfo.id).then(r => {
          // 设置默认地址
          // 姓名
          this.username = this.addressData[0].realname
          // 电话
          this.tel = this.addressData[0].telephone
          // 地址
          this.address = this.addressData[0].province + this.addressData[0].city + this.addressData[0].area +
            this.addressData[0].address
          // 地址列表默认id
          this.chosenAddressId = this.addressData[0].id
        })
      })
    },
  }
</script>
<style scoped>
  .van-icon-edit {
    display: none;
  }

  .van-button {
    width: 75%;
    margin: auto;
    background-color: #409eff;
  }

  .box {
    width: 100%;
    height: 100px;
    transition: 0.3s;
    background-color: wheat;
    box-sizing: border-box;
    display: flex;
  }

  .a {
    width: 25%;
    height: 100px;
    background-color: #409eff;

  }

  .confirm_btn {
    width: 53%;
    height: 40px;
    background-color: #409eff;
    text-align: center;
    color: #fff;
    border-radius: 22px;
    line-height: 40px;
    margin: 0 auto;
    margin-top: 2em;
    cursor: pointer;
  }
</style>